<template>
  <Modal :value="modal" @on-ok="submit" @on-visible-change="vchange" :title="modalTitle" width="800">
    <Form :label-width="110" :model="form" ref="form" :rules="rules">
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="机构" prop="orgId">
            <Select v-model="form.orgId" placeholder="选择机构" @on-change="orgChange" :disabled="modalType !== 1" :transfer="true">
              <OrgTreeOption></OrgTreeOption>
            </Select>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="任务名称" prop="taskName">
            <Input v-model="form.taskName" :disabled="modalType === 0" :maxlength="20" placeholder="输入任务名称"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="排班开始时间" prop="stime">
            <DatePicker v-model="form.stime" :readonly="modalType === 0" :disabled="modalType === 0" @on-change="changeDate($event,'startTime')" :options="datetimeOption"  type="datetime" format="yyyy-MM-dd HH:mm" :transfer="true" placeholder="请选择排班开始时间" style="width: 100%"></DatePicker>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="排班结束时间" prop="etime">
            <DatePicker v-model="form.etime" :readonly="modalType === 0" :disabled="modalType === 0" @on-change="changeDate($event,'endTime')" :options="datetimeOption" type="datetime" format="yyyy-MM-dd HH:mm" :transfer="true" placeholder="请选择排班结束时间" style="width: 100%"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="司机" prop="driverId">
            <Select v-model="form.driverId" :disabled="modalType === 0" :multiple="true" placeholder="请选择司机" :transfer="true">
              <Option v-for="(v,i) in driverList" :key="`sche-driver-${v.id}`" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="车辆" prop="vehicleId">
            <Select v-model="form.vehicleId" :disabled="modalType === 0"  placeholder="请选择车辆" :transfer="true">
              <Option v-for="(v,i) in vehicleList" :key="`sche-vehicle-${v.id}`" :value="v.id">{{v.plateNumber}}</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="24">
          <FormItem label="起点" prop="startAddress">
            <Input v-model="form.startAddress" :disabled="modalType === 0" placeholder="请点击地图标注地理位置" @on-change="getLocation1"></Input>
            <input type="hidden" v-model="form.startLng" />
						<input type="hidden" v-model="form.startLat" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="24">
          <FormItem>
						<div id="js_saddress_map" style="height:250px;"></div>
					</FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="24">
          <FormItem label="终点" prop="endAddress">
            <Input v-model="form.endAddress" :disabled="modalType === 0" placeholder="请点击地图标注地理位置" @on-change="getLocation2"></Input>
            <input type="hidden" v-model="form.endLng" />
						<input type="hidden" v-model="form.endLat" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="24">
          <FormItem>
						<div id="js_eaddress_map" style="height:250px;"></div>
					</FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="24">
          <FormItem label="备注">
            <Input v-model="form.remark" type="textarea" :disabled="modalType === 0" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入备注"></Input>
        </FormItem>
        </Col>
      </Row>
    </Form>
    <div slot="footer">
      <Button @click="closeModal">取消</Button>
      <Button type="primary" v-if="modalType" :loading="isSubmiting" @click="submit">保存</Button>
    </div>
  </Modal>
</template>

<script>
  import {mapState,mapActions,mapMutations} from 'vuex'
  import {post}                             from '@/util/request'
  import moment                             from 'moment'
  import Map                                from '@/plugin/Map'

  let map1 = null;
  let map2 = null;
  let marker1 = null;
  let marker2 = null;
  export default {
    props:['modal','modalTitle','closeModal','modalType'],

    mounted(){
      map1 = new Map('js_saddress_map', {
          resizeEnable: true,
          zoom: 13,
          center: [116.397428, 39.90923]
      });
			AMap.event.addListener(map1, 'click', e => {
				if (this.modalType===0) return;
				let p = e.lnglat;
				if (marker1 === null){
          marker1 = new AMap.Marker({map:map1,position:p});
        } else {
          marker1.setPosition(p);
        }
				this.setStartAddress([p.lng,p.lat]);
			});
      map2 = new Map('js_eaddress_map', {
          resizeEnable: true,
          zoom: 13,
          center: [116.397428, 39.90923]
      });
			AMap.event.addListener(map2, 'click', e => {
				if (this.modalType===0) return;
				let p = e.lnglat;
				if (marker2 === null){
          marker2 = new AMap.Marker({map:map2,position:p});
        } else {
          marker2.setPosition(p);
        }
				this.setEndAddress([p.lng,p.lat]);
			});
    },
    data(){
      return {

        vehicleList:[],
        driverList:[],

        form:{
          id:'',
          orgId:'',
          startAddress:'',
          endAddress:'',
          startLng:null,startLat:null,
          endLng:null,endLat:null,
          driverId:[],
          vehicleId:''
        },
        datetimeOption:{
          disabledDate(date){
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
        rules:{
          orgId:{ required: true, message: '机构必填', trigger: 'change' },
          taskName:{ required: true, message: '任务名称必填', trigger: 'change' },
          stime:{ required: true, type:'date', message: '排班开始时间必填', trigger: 'change' },
          etime:{ required: true, type:'date', message: '排班结束时间必填', trigger: 'change' },
          driverId:{ required: true, type:'array', message: '司机必填', trigger: 'change' },
          vehicleId:{ required: true, message: '车辆必填', trigger: 'change' },
          startAddress:{ required: true, message: '起点必填', trigger: 'change' },
          endAddress:{ required: true, message: '终点必填', trigger: 'change' }
        }
      }
    },
    computed:{
      ...mapState('sche/scheList',['viewData','isModalLoading','isSubmiting']),
      ...mapState('base',['userinfo'])
    },
    watch:{
      viewData(v){
        this.form = {...v};
        if(v.startTime){
          this.form.stime = moment(v.startTime).format();
          this.form.startTime = moment(v.startTime).format("YYYY-MM-DD HH:mm");
        }
        if(v.endTime){
          this.form.etime = moment(v.endTime).format();
          this.form.endTime = moment(v.endTime).format("YYYY-MM-DD HH:mm");
        }
        if(v.receiveUniqueId){
          this.form.driverId = [...v.receiveUniqueId.split(',')];
        }
        map1.clearMap();
        map2.clearMap();
        if (v.startLng && v.startLat) {
					let p = [v.startLng,v.startLat];
					marker1 = new AMap.Marker({map:map1,position:p});
					map1.setCenter(p);
				}
        if (v.endLng && v.endLat) {
					let p = [v.endLng,v.endLat];
					marker2 = new AMap.Marker({map:map2,position:p});
					map2.setCenter(p);
				}
      }
    },
    methods:{
      ...mapActions('sche/scheList',['add','update','getAddress']),
      vchange(e){
        if(!e){
          this.form = {
            id:'',
            orgId:'',
            startAddress:'',
            endAddress:'',
            startLng:null,startLat:null,
            endLng:null,endLat:null,
            driverId:[],
            vehicleId:'',
            stime:'',
            etime:''
          };
          this.vehicleList = [];
          this.driverList = [];
          this.$refs.form.resetFields();
          marker1 = null;
          marker2 = null;
          map1.clearMap();
          map2.clearMap();
          this.closeModal();
        }
      },
      changeDate(v,f){
        if(v)
          this.form[f] = moment(v).format("YYYY-MM-DD HH:mm");
        else
          this.form[f] = '';
      },
      orgChange(v){
        if(v){
          this.loadVehicles(v);
          this.loadDrivers(v);
        }
      },
      async loadVehicles(orgId){
        let res = await post('/common/findVehicleByOrgId',{'orgIds':orgId});
        this.vehicleList = res.data.data;
      },
      async loadDrivers(orgId){
        let res = await post('/common/findDriverByOrgId',{'orgIds':orgId});
        this.driverList = res.data.data;
      },
      async setStartAddress([lng,lat]) {
				this.form.startLng = lng;
				this.form.startLat = lat;
				let res = await this.getAddress([lng,lat]);
				if (res.length > 0) {
					this.form.startAddress = res[0].formattedAddress;
					this.$refs.form.validateField('startAddress');
				}
			},
      getLocation1(e){
				this.form.startLng = null;
				this.form.startLat = null;
				if (marker1 !== null){
					marker1.setMap(null);
					marker1 = null;
				}
				let v = this.form.startAddress;
				let geo = new AMap.Geocoder();
				geo.getLocation(v,(status,result)=>{
					if (status === 'complete'){
						let ad = result.geocodes[0];
						this.form.startLng = ad.location.lng;
						this.form.startLat = ad.location.lat;
						if (marker1 === null){
							marker1 = new AMap.Marker({map:map1,position:ad.location});
						} else {
							marker1.setPosition(ad.location);
						}
						map1.setCenter(ad.location);
					}
				});
			},
      async setEndAddress([lng,lat]) {
				this.form.endLng = lng;
				this.form.endLat = lat;
				let res = await this.getAddress([lng,lat]);
				if (res.length > 0) {
					this.form.endAddress = res[0].formattedAddress;
					this.$refs.form.validateField('endAddress');
				}
			},
      getLocation2(e){
				this.form.endLng = null;
				this.form.endLat = null;
				if (marker2 !== null){
					marker2.setMap(null);
					marker2 = null;
				}
				let v = this.form.endAddress;
				let geo = new AMap.Geocoder();
				geo.getLocation(v,(status,result)=>{
					if (status === 'complete'){
						let ad = result.geocodes[0];
						this.form.endLng = ad.location.lng;
						this.form.endLat = ad.location.lat;
						if (marker2 === null){
							marker2 = new AMap.Marker({map:map2,position:ad.location});
						} else {
							marker2.setPosition(ad.location);
						}
						map2.setCenter(ad.location);
					}
				});
			},
      async submit(){
        let v = await this.$refs.form.validate();
        if(v){
          let res;
          let subForm = {...this.form};
          let jsonArr = [];
          let ths = this;
          subForm.driverId.forEach(function(item,index,arr){
            let driverName = ths.driverList.filter(it=>it.id === item)[0].name;
            let json = {'receiveUniqueId':item,'receiveUniqueName':driverName,'receiveType':1};
            jsonArr.push(json);
          });
          subForm['json'] = JSON.stringify(jsonArr);
          subForm['plateNumber'] = this.vehicleList.filter(it=>it.id === subForm.vehicleId)[0].plateNumber;

          delete subForm.insertTime;
          // delete subForm.stime;
          // delete subForm.etime;
          delete subForm.driverId;
          delete subForm.receiveUniqueId;
          delete subForm.receiveUniqueName;

          if(this.modalType === 1)
            res = await this.add(subForm);
          else
            res = await this.update(subForm);
          if(res.data.success){
            this.closeModal();
            if(this.modalType === 1)
              this.$emit("add");
            else
              this.$emit("edit");
            this.$Message.success('保存成功');
          }else{
            this.$Message.error(res.data.msg);
          }
        }
      }
    }
  }
</script>
